var createError = require('http-errors');
var express = require('express');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var jwt = require('express-jwt')
var fs = require('fs')
var path = require('path')
var cors = require('cors')


var registerRouter = require('./routes/userRegister')
var loginRouter = require('./routes/userLogin')
var reLoginRouter = require('./routes/userReLogin')
var checkQuestRouter = require('./routes/checkQuest')
var enterQuestRouter = require('./routes/enterQuest')
var submitQuestRouter = require('./routes/submitQuest')
var downloadStatisticRouter = require('./routes/downloadStatistic')
var alterPinRouter = require('./routes/alterPin')
var returnOneAnswerRouter = require('./routes/returnOneAnswer')

var questionnairesCreateRouter = require('./routes/questionnairesCreate')
var GetQuestRouter = require('./routes/questionnaires')
var questionnairesDeleteRouter = require('./routes/questionnairesDelete')
var questionnairesEditRouter = require('./routes/questionnairesEdit')
var questionnairesAnalysisRouter = require('./routes/questionnairesAnalysis')
var questionnairesDeleteManyRouter = require('./routes/questionnairesDeleteMany')

var deleteAllAnswersRouter = require('./routes/deleteAllAnswers')
var deleteOneAnswerRouter = require('./routes/deleteOneAnswer')
var returnAllAnswersRouter = require('./routes/returnAllAnswers')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.use(cors());//第一种方法解决跨域
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//鉴权
app.use(jwt({
    secret: fs.readFileSync(path.join(__dirname, './secret/jwt.pem')),
    algorithms: ['RS256'],
}).unless({path: ['/login', '/register', /^\/questionnaires\/.*\/submit/, /^\/questionnaires\/.*\/write/, /^\/questionnaires\/.*\/download/]}))

//处理鉴权的错误
app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        res.status(401).send({
            code: 0,
            msg: "未验证身份"
        })
    }
})


app.post('/register', registerRouter);//用户注册
app.post('/login', loginRouter);//用户登录
app.get('/me', reLoginRouter);//用户重新登录

app.get('/questionnaires/:id/view', checkQuestRouter);//用户查看问卷
app.get('/questionnaires/:opencode/write', enterQuestRouter);//答卷人进去问卷填写
app.post('/questionnaires/:opencode/submit', submitQuestRouter);//答卷人提交问卷
app.get('/questionnaires/:id/download', downloadStatisticRouter)//下载excel
app.delete('/answers', deleteAllAnswersRouter)//删除所有答卷
app.delete('/answers/:id', deleteOneAnswerRouter)//删除单个答卷
app.get('/questionnaires/:id/answers', returnAllAnswersRouter)//返回所有答卷
app.patch('/answers/:id', alterPinRouter)//修改收藏状态

app.use('/questionnaires/create', questionnairesCreateRouter);
app.use('/questionnaires', GetQuestRouter);
app.delete('/questionnaires/:id', questionnairesDeleteRouter)
app.patch('/questionnaires/:id', questionnairesEditRouter)
app.get('/questionnaires/:id/analysis', questionnairesAnalysisRouter)
app.delete('/questionnaires', questionnairesDeleteManyRouter)

app.delete('/answers', deleteAllAnswersRouter)//删除所有答卷
app.delete('/answers/:id', deleteOneAnswerRouter)//删除单个答卷
app.get('/questionnaires/:id/answers', returnAllAnswersRouter)//返回所有答卷
app.get('/answers/:id', returnOneAnswerRouter)//返回单张问卷

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
